<template>
  <el-container class="layout-container">
    <el-aside :width="isCollapse ? '64px' : '280px'" class="aside">
      <div class="logo">
        <img src="../assets/logo.svg" alt="Logo" />
        <span v-show="!isCollapse">问鼎巅峰之路</span>
      </div>
      <el-menu
        :default-active="activeMenu"
        class="el-menu-vertical"
        :collapse="isCollapse"
        background-color="#1f2937"
        text-color="#9ca3af"
        active-text-color="#ffffff"
        :unique-opened="true"
        router
      >
        <el-menu-item index="/dashboard">
          <el-icon><DataLine /></el-icon>
          <template #title>学习概览</template>
        </el-menu-item>
        
        <el-menu-item index="/subject">
          <el-icon><Reading /></el-icon>
          <template #title>学习学科</template>
        </el-menu-item>
        
        <el-menu-item index="/study-plan">
          <el-icon><Calendar /></el-icon>
          <template #title>学习任务</template>
        </el-menu-item>
        
        <el-menu-item index="/study-record">
          <el-icon><Search /></el-icon>
          <template #title>学习记录</template>
        </el-menu-item>
        
        <el-menu-item index="/question-bank">
          <el-icon><Document /></el-icon>
          <template #title>题库管理</template>
        </el-menu-item>
        
        <el-menu-item index="/message-board">
          <el-icon><ChatDotRound /></el-icon>
          <template #title>留言板</template>
        </el-menu-item>
        
        <!-- <el-menu-item index="/backup">
          <el-icon><Upload /></el-icon>
          <template #title>资料管理</template>
        </el-menu-item>
        
        <el-menu-item index="/users">
          <el-icon><User /></el-icon>
          <template #title>用户管理</template>
        </el-menu-item>
        
        <el-menu-item index="/settings">
          <el-icon><Setting /></el-icon>
          <template #title>系统设置</template>
        </el-menu-item> -->
      </el-menu>
    </el-aside>
    
    <el-container>
      <el-header class="header" height="64px">
        <div class="header-left">
          <el-icon class="collapse-btn" @click="isCollapse = !isCollapse">
            <Fold v-if="!isCollapse" />
            <Expand v-else />
          </el-icon>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>{{ currentRoute }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-avatar :size="36" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
              <span>管理员</span>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                <el-dropdown-item command="password">修改密码</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      
      <el-main class="main">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import {
  DataLine,
  Calendar,
  Search,
  Upload,
  User,
  Setting,
  Fold,
  Expand,
  Reading,
  Document,
  ChatDotRound
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const isCollapse = ref(false)

const activeMenu = computed(() => route.path)
const currentRoute = computed(() => {
  const path = route.path
  const routes = {
    '/dashboard': '学习概览',
    '/subject': '学习学科',
    '/study-plan': '学习任务',
    '/study-record': '学习记录',
    '/question-bank': '题库管理',
    '/message-board': '留言板',
    '/backup': '资料管理',
    '/users': '用户管理',
    '/settings': '系统设置'
  }
  return routes[path] || '未知页面'
})

const currentConnectionId = ref('')

const handleConnectionSelected = (event) => {
  currentConnectionId.value = event.detail
}

const handleCommand = async (command) => {
  if (command === 'logout') {
    try {
      await ElMessageBox.confirm('确认要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      const response = await axios.post('/api/user/logout')
      if (response.data.code === '200' || response.data.code === 200) {
        // 清除本地存储的用户信息
        localStorage.removeItem('user')
        ElMessage({
          message: '已成功退出登录',
          type: 'success',
          duration: 3000,
          showClose: true
        })
        // 跳转到登录页
        router.push('/login')
      } else {
        ElMessage({
          message: response.data.message || '退出失败',
          type: 'error',
          duration: 3000,
          showClose: true
        })
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('退出登录失败:', error)
        ElMessage({
          message: error.response?.data?.message || '退出失败，请稍后重试',
          type: 'error',
          duration: 3000,
          showClose: true
        })
      }
    }
  }
}

const statTime = ref({
  today: 0,
  week: 0,
  month: 0
})

// 秒转"X小时Y分"
const formatHourMinute = (seconds) => {
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  return `${h > 0 ? h + '小时' : ''}${m > 0 ? m + '分' : (h === 0 ? '0分' : '')}`
}

// 获取统计数据
const fetchStatTime = async () => {
  try {
    const res = await axios.get('/api/study/time')
    if (res.data.code === '200') {
      statTime.value = res.data.data || { today: 0, week: 0, month: 0 }
    }
  } catch (e) {
    console.error('获取统计时长失败', e)
  }
}

onMounted(() => {
  window.addEventListener('connection-selected', handleConnectionSelected)
  fetchStatTime()
})

onUnmounted(() => {
  window.removeEventListener('connection-selected', handleConnectionSelected)
})
</script>

<style scoped>
.layout-container {
  min-height: 100vh;
  width: 100vw;
  background-color: #f3f4f6;
  display: flex;
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
}

.aside {
  background-color: #1f2937;
  height: 100vh;
  transition: width 0.3s;
  overflow: hidden;
  flex-shrink: 0;
}

.logo {
  height: 64px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  background-color: #111827;
  color: #fff;
  font-size: 20px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
}

.logo img {
  width: 36px;
  height: 36px;
  margin-right: 16px;
  flex-shrink: 0;
}

.header {
  background-color: #ffffff;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 32px;
}

.collapse-btn {
  font-size: 24px;
  cursor: pointer;
  color: #4b5563;
  transition: color 0.3s;
}

.collapse-btn:hover {
  color: #1f2937;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  color: #4b5563;
  font-size: 16px;
}

.main {
  background-color: #f3f4f6;
  padding: 32px;
  overflow-y: auto;
  flex: 1;
  height: calc(100vh - 64px);
  width: 100%;
}

:deep(.el-menu) {
  border-right: none;
}

:deep(.el-menu-item),
:deep(.el-sub-menu__title) {
  height: 50px !important;
  line-height: 50px !important;
  font-size: 16px !important;
  color: #9ca3af !important;
}

:deep(.el-menu-item.is-active) {
  color: #ffffff !important;
  background-color: #374151 !important;
}

:deep(.el-menu-item:hover),
:deep(.el-sub-menu__title:hover) {
  color: #ffffff !important;
  background-color: #374151 !important;
}

:deep(.el-sub-menu.is-active .el-sub-menu__title) {
  color: #ffffff !important;
}

:deep(.el-menu--popup) {
  background-color: #1f2937 !important;
  padding: 0 !important;
  min-width: 180px !important;
  border: none !important;
}

:deep(.el-menu--popup .el-menu-item) {
  color: #9ca3af !important;
  padding-left: 20px !important;
}

:deep(.el-menu--popup .el-menu-item.is-active),
:deep(.el-menu--popup .el-menu-item:hover) {
  color: #ffffff !important;
  background-color: #374151 !important;
}

:deep(.el-breadcrumb__inner) {
  color: #4b5563 !important;
  font-weight: normal;
  font-size: 15px;
}

:deep(.el-breadcrumb__inner.is-link:hover) {
  color: #1f2937 !important;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style> 